package com.listener;

import java.util.ArrayList;
import java.util.List;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * 监听网络状态的改变
 * 
 * @author wangyuhong
 * 
 */
public class NetStateReceiver extends BroadcastReceiver {
	private boolean mFirstInit = false;
	private int     TOAST_LONG=2000;
	private List<NetChangeListener> mListeners = new ArrayList<NetChangeListener>();

	public void setNetChangeListener(NetChangeListener listener) {
		mListeners.add(listener);
	}

	public void removeNetChangeListener(NetChangeListener listener) {
		mListeners.remove(listener);
	}
	
	public void destroy(){
		if(mListeners!=null){
			mListeners.clear();
		}
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = cm.getActiveNetworkInfo();
			if (info != null && info.isAvailable()) {
				String name = info.getTypeName();
				if(mFirstInit){
					mFirstInit = false ;
					int size = mListeners.size();
					for (int i = 0; i < size; i++) {
						NetChangeListener listener = mListeners.get(i);
						if (listener != null) {
							listener.onNetChange(true);
						}
					}
//					ReconnectionManager.resetAttempts();
					Toast.makeText(context, "网络已恢复,连接到" + name + "网络",
							TOAST_LONG).show();
				}
			} else {
				mFirstInit = true ;
				int size = mListeners.size();
				for (int i = 0; i < size; i++) {
					NetChangeListener listener = mListeners.get(i);
					if (listener != null) {
						listener.onNetChange(false);
					}
				}
				Toast.makeText(context, "当前网络不可用,请检查网络设置",TOAST_LONG)
						.show();
			}
		}
	}

}
